home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / FDF101.ARJ / ELIB.ZOO / getopt.c < prev    next >
C/C++ Source or Header  |  1992-04-30  |  1KB  |  70 lines

  1. #include <string.h>
  2.  
  3. /*LINTLIBRARY*/
  4. #ifndef NULL
  5. #define NULL    0
  6. #endif
  7. #ifndef EOF
  8. #define EOF    (-1)
  9. #endif
  10. #define ERR(s, c)    if(opterr){\
  11.     char errbuf[3];\
  12.     errbuf[0] = c; errbuf[1] = '\r'; errbuf[2] = '\n';\
  13.     (void) write(2, argv[0], (unsigned)strlen(argv[0]));\
  14.     (void) write(2, s, (unsigned)strlen(s));\
  15.     (void) write(2, errbuf, 3);}
  16.  
  17. extern int strcmp();
  18. extern char *strchr();
  19.  
  20. int    opterr = 1;
  21. int    Optind = 1;
  22. int    optopt;
  23. char    *optarg;
  24.  
  25.  
  26. int
  27. getopt(int argc, char **argv, char *opts)
  28. {
  29.     static int sp = 1;
  30.     register int c;
  31.     register char *cp;
  32.  
  33.     if(sp == 1)
  34.         if(Optind >= argc ||
  35.            argv[Optind][0] != '-' || argv[Optind][1] == '\0')
  36.             return(EOF);
  37.         else if(strcmp(argv[Optind], "--") == NULL) {
  38.             Optind++;
  39.             return(EOF);
  40.         }
  41.     optopt = c = argv[Optind][sp];
  42.     if(c == ':' || (cp=strchr(opts, c)) == NULL) {
  43.         ERR(": illegal option -- ", c);
  44.         if(argv[Optind][++sp] == '\0') {
  45.             Optind++;
  46.             sp = 1;
  47.         }
  48.         return('\0');
  49.     }
  50.     if(*++cp == ':') {
  51.         if(argv[Optind][sp+1] != '\0')
  52.             optarg = &argv[Optind++][sp+1];
  53.         else if(++Optind >= argc) {
  54.             ERR(": option requires an argument -- ", c);
  55.             sp = 1;
  56.             return('\0');
  57.         } else
  58.             optarg = argv[Optind++];
  59.         sp = 1;
  60.     } else {
  61.         if(argv[Optind][++sp] == '\0') {
  62.             sp = 1;
  63.             Optind++;
  64.         }
  65.         optarg = NULL;
  66.     }
  67.     return(c);
  68. }
  69.  
  70.